<?php

class TransactionmasterController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
//	public $layout='//layouts/column2';
    public $layout = '//layouts/eastsouthwest';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index', 'view'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create', 'update', 'autocomplete', 'addrow', 'autocompleteAcledger', 'init', 'accountingvouchers', 'createAccountingVoucher', 'validateAccountingVoucher'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('popupview', 'admin'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('popupview', 'admin', 'delete'),
                'users' => array('admin'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionAutocomplete() {
        $res = array();

        if (isset($_GET['term'])) {
            $match = addcslashes($_GET['term'], '%_');
            $criteria = new CDbCriteria(array(
                        'condition' => 'transactionmastervoucherdate LIKE :transactionmastervoucherdate',
                        'params' => array(':transactionmastervoucherdate' => "%$match%")
                    ));
            $models = Transactionmaster::model()->findAll($criteria);
            foreach ($models as $model) {
                $res[] = $model->transactionmastervoucherdate;
            }
        }

        echo CJSON::encode($res);
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        if (isset($_REQUEST['isAjaxRequest']) && $_REQUEST['isAjaxRequest'] == 1) {
            Yii::app()->clientscript->scriptMap['jquery.js'] = false;
            Yii::app()->clientscript->scriptMap['jquery-ui.min.js'] = false;
            echo $this->renderPartial('view', array('model' => $this->loadModel($id)), true, true);
            Yii::app()->end();
            exit();
        } else {
            $this->render('view', array(
                'model' => $this->loadModel($id),
            ));
        }
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Transactionmaster;

        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);

        if (isset($_POST['Transactionmaster'])) {
            $model->attributes = $_POST['Transactionmaster'];
            $status = 'Failure';
            if ($model->save()) {
                $status = 'Success';
            }

            echo CJSON::encode(array(
                'status' => $status,
            ));
            exit;
        } else {
            if (isset($_REQUEST['isAjaxRequest']) && $_REQUEST['isAjaxRequest'] == 1) {
                Yii::app()->clientscript->scriptMap['jquery.js'] = false;
                Yii::app()->clientscript->scriptMap['jquery-ui.min.js'] = false;
                echo $this->renderPartial('_form', array('model' => $model), true, true);
                exit();
            }
        }
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);

        if (isset($_POST['Transactionmaster'])) {
            $model->attributes = $_POST['Transactionmaster'];
            $status = 'Failure';
            if ($model->save()) {
                $status = 'Success';
            }

            echo CJSON::encode(array(
                'status' => $status,
            ));
            exit;
        } else {
            if (isset($_REQUEST['isAjaxRequest']) && $_REQUEST['isAjaxRequest'] == 1) {
                Yii::app()->clientscript->scriptMap['jquery.js'] = false;
                Yii::app()->clientscript->scriptMap['jquery-ui.min.js'] = false;
                echo $this->renderPartial('_form', array('model' => $model), true, true);
                exit();
            }
        }
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider('Transactionmaster');
        $this->render('index', array(
            'dataProvider' => $dataProvider,
        ));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Transactionmaster('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Transactionmaster']))
            $model->attributes = $_GET['Transactionmaster'];

        if (isset($_REQUEST['isAjaxRequest']) && $_REQUEST['isAjaxRequest'] == '1') {
            $this->renderPartial('admin', array('model' => $model, 'isAjaxRequest' => $_REQUEST['isAjaxRequest']), false, true);
        } else {
            $this->render('admin', array(
                'model' => $model,
            ));
        }
    }

    /**
     * Manages popupview.
     */
    public function actionPopupview() {
        $model = new Transactionmaster('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Transactionmaster']))
            $model->attributes = $_GET['Transactionmaster'];

        $params = array(
            'model' => $model,
            'id' => isset($_REQUEST['id']) ? $_REQUEST['id'] : '',
            'isAjaxRequest' => 1,
        );

        Yii::app()->clientscript->scriptMap['jquery.js'] = false;
        if (isset($_REQUEST['isAjaxRequest']) && $_REQUEST['isAjaxRequest'] == '1') {
            //        if (!isset($_GET['ajax'])){
            $this->renderPartial('popupview', $params, false, true);
            Yii::app()->end();
        } else {
            $this->render('popupview', $params);
        }
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = Transactionmaster::model()->findByPk((int) $id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {  
        if (isset($_POST['ajax']) && ($_POST['ajax'] === 'transactionmaster-form' || $_POST['ajax'] === 'accountingvouchers-form')) {
            echo CActiveForm::validate($model, NULL, true);
            syslog(LOG_WARNING, 'val: ' . count($model->getErrors()) . ' - ' . print_r($model->getErrors(), true));
            Yii::app()->end();
//                Yii::app()->end();
        }
    }

    public function gridAcledger($data, $row) {

        $res = $this->widget('zii.widgets.jui.CJuiAutoComplete', array(
            'name' => 'transactiondetails[' . $row . '][acledger]',
            'value' => $data['acledger'],
            //'model' => $model, 
            //'id' => 'Acledger_acgroupname',
            'theme' => 'bgscstpc',
            'source' => $this->createUrl('acledger/autocomplete'),
            // additional javascript options for the autocomplete plugin
            'options' => array(
                'showAnim' => 'fold',
            ),
            'htmlOptions' => array(
            )
                ), true);
        return $res;
    }

    public function getCredit() {
        $vouchers = Yii::app()->session['vouchers'];
        $credit = 0;
        foreach ($vouchers as $row) {
            $credit += $row['credit'];
        }
        return number_format((float) $credit, 2, '.', '');
    }

    public function getDebit() {
        $vouchers = Yii::app()->session['vouchers'];
        $debit = 0;
        foreach ($vouchers as $row) {
            $debit += $row['debit'];
        }
        return number_format((float) $debit, 2, '.', '');
    }

    public function actionValidateAccountingVoucher() {
                          
        syslog(LOG_WARNING, 'actionValidateAccountingVoucher() ...');        
        $model = new Transactionmaster;
        $status = "Success";

        // Uncomment the following line if AJAX validation is needed
        echo CActiveForm::validate($model, NULL, true);        
//        if(count($model->getErrors()) > 0){
//            $status = "Error";
//        }        
//        else{
//            $status = "Success";            
//        }
//        echo CJSON::encode(array(
//            'status' =>  'Success',
//        ));
        Yii::app()->end();

//        $errorMessages = CActiveForm::validate($model, NULL, true);
//        if(count($model->getErrors()) > 0){
//            echo $errorMessages;
//            echo CJSON::encode(array(
//                'status' => 'Error',
//            ));
//            //$model->clearErrors();
//            Yii::app()->end();
//            exit;
//        }
//        else{
//            echo CJSON::encode(array(
//                'status' => 'Success',
//            ));
//            //$model->clearErrors();
//            Yii::app()->end();
//            exit;
//        }
        
        
    }
    
    
    public function actionAddrow() {
        syslog(LOG_WARNING, 'after Addrow...');        
        $model = new Transactionmaster;

        // Uncomment the following line if AJAX validation is needed
//        syslog(LOG_WARNING, 'activeform::validate::: : ' . CActiveForm::validate($model, NULL, true));
        $errorMessages = CActiveForm::validate($model, NULL, true);
//        syslog(LOG_WARNING, 'activeform::validate::: : ' . count($model->getErrors()) . ' - ' .  $errorMessages);
        if(count($model->getErrors()) > 0){
            syslog(LOG_WARNING, 'val--: ' . count($model->getErrors()) . ' - ' . print_r($model->getErrors(), true));
            echo $errorMessages;
            echo CJSON::encode(array(
                'status' => 'Error',
            ));
            //$model->clearErrors();
            Yii::app()->end();
            exit;
        }
        else{
//            Yii::app()->end();            
        }
//            syslog(LOG_WARNING, 'val---: ' . count($model->getErrors()) . ' - ' . print_r($model->getErrors(), true));
//            Yii::app()->end();
        syslog(LOG_WARNING, 'after validation... ');

        if (isset($_POST['Transactionmaster'])) {
            $model->attributes = $_POST['Transactionmaster'];
//            syslog(LOG_WARNING, 'Transactionmaster...' . $_POST['Transactionmaster']['acledger']);
        }        
        $vouchers = Yii::app()->session['vouchers'];
        $transactionAmount = number_format((float) $_POST['Transactionmaster']['transactionamount'], 2, '.', '');
        if ($_POST['id'] >= 0) {
//            $vouchers[$_POST['id']] = array('id' => $_POST['id'], 'transactioncrdr' => $_POST['transactioncrdr'], 'acledger' => $_POST['acledger'], 'transactionamount' => $transactionAmount, 'credit' => $_POST['transactioncrdr'] == 'CR' ? $transactionAmount : '', 'debit' => $_POST['transactioncrdr'] == 'DR' ? $transactionAmount : '');
            $vouchers[$_POST['id']] = array('id' => $_POST['id'], 'transactioncrdr' => $_POST['Transactionmaster']['transactioncrdr'], 'acledger' => $_POST['Transactionmaster']['acledger'], 'transactionamount' => $transactionAmount, 'credit' => $_POST['Transactionmaster']['transactioncrdr'] == 'CR' ? $transactionAmount : '', 'debit' => $_POST['Transactionmaster']['transactioncrdr'] == 'DR' ? $transactionAmount : '');
        } else {
//            $vouchers[count($vouchers)] = array('id' => count($vouchers), 'transactioncrdr' => $_POST['transactioncrdr'], 'acledger' => $_POST['acledger'], 'transactionamount' => $transactionAmount, 'credit' => $_POST['transactioncrdr'] == 'CR' ? $transactionAmount : '', 'debit' => $_POST['transactioncrdr'] == 'DR' ? $transactionAmount : '');
            $vouchers[count($vouchers)] = array('id' => count($vouchers), 'transactioncrdr' => $_POST['Transactionmaster']['transactioncrdr'], 'acledger' => $_POST['Transactionmaster']['acledger'], 'transactionamount' => $transactionAmount, 'credit' => $_POST['Transactionmaster']['transactioncrdr'] == 'CR' ? $transactionAmount : '', 'debit' => $_POST['Transactionmaster']['transactioncrdr'] == 'DR' ? $transactionAmount : '');
        }
        Yii::app()->session['vouchers'] = $vouchers;
        echo CJSON::encode(array(
            'status' => 'Success',
            'credit' => $this->getCredit(),
            'debit' => $this->getDebit(),
        ));
        exit;
    }

    public function actionInit() {
        Yii::app()->session['rowcount'] = 1;
        Yii::app()->session['vouchers'] = NULL;
    }

    public function actionAccountingvouchers($idtransactionmaster = 0, $idvouchertype = 0) {
        syslog(LOG_WARNING, "TranCont -> accountingvouchers->idvouchertype->$idvouchertype");
        $model = new Transactionmaster;

        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);

        if (isset($_POST['Transactionmaster'])) {
            $model->attributes = $_POST['Transactionmaster'];
            $status = 'Failure';
//            if ($model->save()) {
//                $status = 'Success';
//            }

            echo CJSON::encode(array(
                'status' => $status,
            ));
            exit;
        } else {

            if (isset($_REQUEST['isAjaxRequest']) && $_REQUEST['isAjaxRequest'] == 1) {

                if ($idtransactionmaster > 0) {
                    $transactionmaster = Transactionmaster::model()->find('idtransactionmaster=:idtransactionmaster', array(':idtransactionmaster' => $idtransactionmaster));
                    if (isset($transactionmaster)) {
                        $model->idvouchertype = $transactionmaster->idvouchertype;
                        $vouchertype = $transactionmaster->idvouchertype0->vouchertype;
                        $model = $transactionmaster;
                    }
                } else {
                    $transactionmaster = new Transactionmaster;
                    syslog(LOG_WARNING, "TranCont -> inside iff... " . $idvouchertype);
                    if ($idvouchertype > 0) {
                        $vouchertype = Vouchertype::model()->find('idvouchertype=:idvouchertype', array(':idvouchertype' => $idvouchertype));
                        if (isset($vouchertype)) {
                            $model->idvouchertype = $vouchertype->idvouchertype;
                            $vouchertype = $vouchertype->vouchertype;
                            //$model = $transactionmaster;
                        }
                    }
                }
                syslog(LOG_WARNING, "TranCont -> idvouchertype..." . $idvouchertype . ' - ' . $model->idvouchertype);
                
                echo $this->renderPartial('accountingvouchers', array('model' => $model, 'dataProvider' => $model->transactiondetailsDataProvider($idtransactionmaster), 'type' => $vouchertype, 'transactionmaster' => $transactionmaster), true, true);
                exit();
            }
        }
    }

    public function actionAutocompleteAcledger() {
        $res = array();

        if (isset($_GET['term'])) {
            $type = isset($_GET['type']) ? $_GET['type'] : '';
            $transactioncrdr = isset($_GET['transactioncrdr']) ? $_GET['transactioncrdr'] : '';
            $rulescolumn = strtolower($type . $transactioncrdr);

            $match = addcslashes($_GET['term'], '%_');
            $criteria = new CDbCriteria(array(
                        'with' => array('idacgroup0', 'idacgroup0.idrules0'),
                        'condition' => 'acledgername LIKE :acledgername And idrules0.' . $rulescolumn . '=1',
                        'params' => array(':acledgername' => "%$match%")
                    ));
            $models = Acledger::model()->findAll($criteria);
            foreach ($models as $model) {
                $res[] = $model->acledgername;
            }
        }
        echo CJSON::encode($res);
    }
    
    public function saveTransactiondetails($idtransactionmaster) {
        
        if($idtransactionmaster != '' ){
            $criteria = new CDbCriteria(array(
                        'condition' => 'idtransactionmaster = :idtransactionmaster',
                        'params' => array(':idtransactionmaster' => $idtransactionmaster)
                    ));
            Transactiondetails::model()->deleteAll($criteria);
        }
        
        $vouchers = Yii::app()->session['vouchers'];
        foreach ($vouchers as $row) {
            syslog(LOG_WARNING, 'rows...' . print_r($row, true));
            $criteria = new CDbCriteria(array(
                        'condition' => 'acledgername = :acledgername',
                        'params' => array(':acledgername' => $row['acledger'])
                    ));
            $acledger = Acledger::model()->find($criteria);
            
            syslog(LOG_WARNING, 'transactiondetails - row...' . $acledger['idacledger'] . ' ' . $idtransactionmaster);
            $transactiondetails = new Transactiondetails;
            syslog(LOG_WARNING, 'okkk1');
            $transactiondetails->idtransactionmaster = $idtransactionmaster;
            syslog(LOG_WARNING, 'okkk2');
            $transactiondetails->idacledger = $acledger['idacledger'];
            syslog(LOG_WARNING, 'okkk3');
            $transactiondetails->transactionamount = $row['transactionamount'];
            syslog(LOG_WARNING, 'okkk4');
            $transactiondetails->transactioncrdr = $row['transactioncrdr'];
            syslog(LOG_WARNING, 'okkk5');
//            syslog(LOG_WARNING, 'transactiondetails...' . print_r($transactiondetails, true));
            $transactiondetails->save(false);
        }
    }


    public function actionCreateAccountingVoucher() {
        $model = new Transactionmaster;
        $this->performAjaxValidation($model);
        syslog(LOG_WARNING, 'after ajaxvalidate...');

        if (isset($_POST['Transactionmaster'])) {
            $model->attributes = $_POST['Transactionmaster'];
//            echo CActiveForm::validate($model);
//            Yii::app()->end();
//            syslog(LOG_WARNING, print_r($_POST['Transactionmaster'], true));
        }
        
        $status = 'Success';
        $message = '';
        $vouchers = Yii::app()->session['vouchers'];
        $idtransactionmaster = isset($_POST['idtransactionmaster']) ? $_POST['idtransactionmaster'] : '' ;
        $idvouchertype = isset($_POST['idvouchertype']) ? $_POST['idvouchertype'] : '';
        $userObject = Yii::app()->getModule('user')->user(); // Public Properties: id, username, email, createtime, lastvisit and profile relation
        $profileObject = $userObject->profile;               // Your custom fields (Default: firstname, lastname, about)        
        $transactionmastervoucherdate = $userObject->profile->transactiondate;
        $transactionmasternarration = isset($_POST['Transactionmaster']['transactionmasternarration']) ? $_POST['Transactionmaster']['transactionmasternarration'] : '';
        $isNewRecord = $idtransactionmaster == '' ? true : false;
        syslog(LOG_WARNING, "Voucher Cnt: " . count($vouchers) . ' ' . $this->getCredit() . ' ' . $this->getDebit() . ' - ' . $model->transactioncrdr . ' - idtransactionmaster: ' . $idtransactionmaster . ' - ' . $isNewRecord);
        if (count($vouchers) == 0) {
            $status = 'Failure';
            $message = Yii::t('application', 'No Voucher Entry!');
        } else {
            if($this->getCredit() != $this->getDebit()){
                $status = 'Failure';
                $message = Yii::t('application', 'Debit Credit not equal!');
            }
            else{
//                $transactionmasternarration = isset($_POST['transactionmasternarration']) ? $_POST['transactionmasternarration'] : '';
//                if($transactionmasternarration == ''){
//                    $status = 'Failure';
//                    $message = Yii::t('application', 'Empty {attribute}!', array('{attribute}' => Yii::t('application', 'Transactionmasternarration')));
//                }
//                syslog(LOG_WARNING, $profileObject->transactiondate . ' ' . $transactionmasternarration . ' ' . $idvouchertype . ' ' . (isset($idtransactionmaster) && $idtransactionmaster != '' ? "set.." : "not set..") . ' ' . print_r($vouchers, true));
            }
        }
        if($status == 'Success'){            
//            syslog(LOG_WARNING, $userObject->profile->transactiondate);
            $transactionmaster = NULL;;
            if($isNewRecord){
                syslog(LOG_WARNING, 'NEW');
                $transactionmaster = new Transactionmaster;         
                $transactionmaster->transactionmastervoucherdate = $transactionmastervoucherdate;
                $transactionmaster->idvouchertype = $idvouchertype;
            }
            else{
                syslog(LOG_WARNING, 'OLD - ' . $idtransactionmaster);
                $transactionmaster = Transactionmaster::model()->findByPk((int) $idtransactionmaster);
//                $transactionmaster->idtransactionmaster = $idtransactionmaster;
            }
            $transactionmaster->transactionmasternarration = $transactionmasternarration;
            syslog(LOG_WARNING, 'ERROR CNT - ' . count($transactionmaster->getErrors()) . ' - ' . $transactionmaster->transactionmasternarration );
            if($transactionmaster->save(false)){
                syslog(LOG_WARNING, 'pkey - ' . $transactionmaster->getPrimaryKey());
                $idtransactionmaster = $transactionmaster->getPrimaryKey();
                $this->saveTransactiondetails($idtransactionmaster);
            }
            else{
                $status = 'Failure';
                $message = Yii::t('application', 'db error...!');                
//                syslog(LOG_WARNING, 'ERRORS - ' . print_r($transactionmaster->getErrors(), true));
                syslog(LOG_WARNING, 'ERRORS - ' . count($transactionmaster->getErrors()));                
            }
            
        }
        echo CJSON::encode(array(
            'status' => $status,
            'message' => $message,
        ));
        exit;
    }

}
